﻿/*********************************************************************************/
/**    Sims3Pack Readme Generator                                               **/
/**    Copyright (C) 2012  Anja Knackstedt                                      **/
/**                                                                             **/
/**    This program is free software: you can redistribute it and/or modify     **/
/**    it under the terms of the GNU General Public License as published by     **/
/**    the Free Software Foundation, either version 3 of the License, or        **/
/**    (at your option) any later version.                                      **/
/**                                                                             **/
/**    This program is distributed in the hope that it will be useful,          **/
/**    but WITHOUT ANY WARRANTY; without even the implied warranty of           **/
/**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            **/
/**    GNU General Public License for more details.                             **/
/**                                                                             **/
/**    You should have received a copy of the GNU General Public License        **/
/**    along with this program.  If not, see <http://www.gnu.org/licenses/>.    **/
/**                                                                             **/
/*********************************************************************************/




using System;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using Sims3PackReadmeGenerator.Gui;
using Sims3PackReadmeGenerator.language;
using Sims3PackReadmeGenerator.Properties;
using System.IO;
using System.Xml;

namespace Sims3PackReadmeGenerator
{
    static class Program
    {       
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            checkForSettingUpgrade();

            string missingFiles;

            if (hasNeededFoldersAndFiles(out missingFiles))
            {
                

                // Sets the UI language to settinsg value when existend             
                if (!string.IsNullOrEmpty(Settings.Default.Language))
                {
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo(Settings.Default.Language);
                    //MessageBox.Show("Settings lang" + Settings.Default.Language); 
                }
                else if (Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName == "de")
                {
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("de");
                }
                else
                {
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");                    
                }

                Sims3PackReadmeGenGui gui = new Sims3PackReadmeGenGui();

                //form has to know its language for displaying the content
                if (Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName == "de")
                {
                    gui.GuiLanguage = Languages.de;           
                }
                else
                {
                    gui.GuiLanguage = Languages.en;                      
                }

                try
                {                    
                    Application.Run(gui);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format(errors.errorCommon, ex.Message /*+ "\n\n" + ex.Source + "\n\n" + ex.StackTrace*/), errors.errorsCommenTitle);
                }
            }
            else
            {
                MessageBox.Show(string.Format(  errors.errorFilesMissing, missingFiles),
                                                errors.errorFilesMissingTitle,
                                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// upgrade settings when neccessary
        /// </summary>
        private static void checkForSettingUpgrade()
        {            
            if (Settings.Default.UpgradeRequired)
            {
                Settings.Default.Upgrade();
                Settings.Default.UpgradeRequired = false;
                Settings.Default.Save();
            }
        }

        /// <summary>
        /// checks if all needed data is available at startup
        /// </summary>
        /// <returns></returns>
        private static bool hasNeededFoldersAndFiles(out string missingFiles)
        {
            bool hasAllNeededFoldersFiles = true;
            missingFiles = string.Empty;

            //check if main user dir exits
            if (!Directory.Exists(FilePaths.appMyDocPath))
            {
                createUserMainDir();
            }
            else
            {
                //check if user data dir exits
                if (!Directory.Exists(FilePaths.userdataPath))
                {
                    createUserDataDir();
                }
                else
                {
                    //check if custom layout dir exits
                    if (!Directory.Exists(FilePaths.customLayoutPath))
                    {
                        Directory.CreateDirectory(FilePaths.customLayoutPath);
                    }
                }
            }

            //check if needed data exits

            if (!File.Exists(FilePaths.addonXmlPath))
            {
                hasAllNeededFoldersFiles = false;
                missingFiles += FilePaths.addonXmlPath + "\n";
            }

            if (!File.Exists(FilePaths.gamerefXmlPath))
            {
                hasAllNeededFoldersFiles = false;
                missingFiles += FilePaths.gamerefXmlPath + "\n";
            }

            if (!File.Exists(FilePaths.standardCollectionLayoutGermanPath))
            {
                hasAllNeededFoldersFiles = false;
                missingFiles += FilePaths.standardCollectionLayoutGermanPath + "\n";
            }

            if (!File.Exists(FilePaths.standardCollectionLayoutEnglishPath))
            {
                hasAllNeededFoldersFiles = false;
                missingFiles += FilePaths.standardCollectionLayoutEnglishPath + "\n";
            }

            return hasAllNeededFoldersFiles;
        }

        private static void createUserDataDir()
        {            
            Directory.CreateDirectory(FilePaths.userdataPath);
            Directory.CreateDirectory(FilePaths.customLayoutPath);

            createEmptyBadCCFile();
            createEmptyKnownpackgesFile();
        }

        /// <summary>
        /// creates default user data
        /// </summary>
        private static void createUserMainDir()
        {
            Directory.CreateDirectory(FilePaths.appMyDocPath);
            Directory.CreateDirectory(FilePaths.userdataPath);
            Directory.CreateDirectory(FilePaths.customLayoutPath);

            createEmptyBadCCFile();
            createEmptyKnownpackgesFile();
        }

        /// <summary>
        /// creates an empty badcc.xml file
        /// </summary>
        private static void createEmptyBadCCFile()
        {
            XmlDocument doc = createXmlDocument("badcc");
            doc.Save(FilePaths.badCCXmlDataPath);
        }

        /// <summary>
        /// creates an empty packages.xml file
        /// </summary>
        private static void createEmptyKnownpackgesFile()
        {
            XmlDocument doc = createXmlDocument("packages");
            doc.Save(FilePaths.knownCCXmlDataPath);
        }

        /// <summary>
        /// creates a new xml document with root of the given name
        /// </summary>
        /// <param name="rootName">root name</param>
        /// <returns></returns>
        private static XmlDocument createXmlDocument(string rootName)
        {
            
            XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);
            XmlElement root = doc.CreateElement(rootName);
            doc.AppendChild(root);

            return doc;
        }
    }
}
